import data from "./data";
import './main'
interface OptionState {
  root: HTMLElement;
  openSubChildren?: boolean
}

// 类 泛型
class Tree {
  // 属性属性
  private list: typeof data;
  option: OptionState
  constructor(list: typeof data, option: OptionState) {
    // 默认参数
    const defaultOption = {
      openSubChildren: true
    }
    // 合并参数
    option = Object.assign(defaultOption, option)
    this.option = option
    this.list = list;

		this.init()
  }
  // 初始化
  init() {
    this.render(this.list)
		this.bindEvent();
  }
  render(list: typeof data) {
    this.option.root.innerHTML = `
      <ul>
        ${list.map(v => {
          return `<li>
						<span>${v.name}</span>
						<ul style="display: ${this.option.openSubChildren ? 'block': 'none'}">
							${v.children && v.children.map(v => {
								return `<li>
									<span>${v.name}</span>
									<ul>
										${v.children ? v.children.map(v => {
											return `<li>
												<span>${v.name}</span>
												
											</li>`
										}).join('') : ''}
									</ul>
								</li>`
							}).join('')}
						</ul>
					</li>`
        }).join('')}
      </ul>
    `
  }
  // 私有方法
  private bindEvent() {
		this.option.root.addEventListener('click', e => {
			const tar = e.target;
			if((tar as HTMLElement).nodeName === 'SPAN') {
				const el = (tar as HTMLElement).nextElementSibling
				if(el) {
					if((el as HTMLElement).style.display === 'block') {
						(el as HTMLElement).style.display = 'none'
					} else {
						(el as HTMLElement).style.display = 'block'
					}
				}
			}
		})
  }
}

new Tree(data, {
	root: document.querySelector('#root') as HTMLElement,
	openSubChildren: false
});
